﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Utils.Common
{
   public class  PropertyHelper
    {


        public static object GetValue(object obj, string propertyName)
        {
            Type type = obj.GetType(); //获取类型
            System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName); //获取指定名称的属性
            if(propertyInfo!=null)
              return  propertyInfo.GetValue(obj, null); //获取属性

            return null;
        }
        public static bool SetValue(object obj, string propertyName, object value)
        {
            try
            {
                Type type = obj.GetType(); //获取类型
                System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName); //获取指定名称的属性

                propertyInfo.SetValue(obj, value, null); //给对应属性赋值

                return true;
            }
            catch {

                return false;
            }
        }

 
        public static string GetDescription(Type type, string propertyName)
        {
            try
            {
                //获取类型
                System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName); //获取指定名称的属性
                DescriptionAttribute descAttr = Attribute.GetCustomAttribute(propertyInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
                return descAttr?.Description ?? "";
            }
            catch
            {
                return "";
            }
        }

    }
}
